from .TextGenerationAssistant import TextGenerationAssistant
from .VoiceAssistant import VoiceAssistant
from .ImageGenerationAssistant import ImageGenerationAssistant
from .DataAnalysisAssistant import DataAnalysisAssistant
from .TranslationAssistant import TranslationAssistant

class AIManager:
    """AI助手管理器类，用于管理所有的AI助手"""
    
    def __init__(self):
        self._assistants = []  # 存储助手的列表
        self._MAX_SIZE = 100  # 最大容量
        self.initialize_default_assistants()
    
    def initialize_default_assistants(self):
        """初始化一些默认的AI助手"""
        self.add_assistant(VoiceAssistant("101", "小智", "v1.2", True, 85, "女声", True))
        self.add_assistant(TextGenerationAssistant("102", "文小助", "v2.0", True, 92, "中文/英文", True))
        self.add_assistant(ImageGenerationAssistant("103", "图灵", "v1.5", False, 88, "1024x768", 20))
        self.add_assistant(DataAnalysisAssistant("104", "数小析", "v1.0", True, 79, "CSV/Excel/JSON", True))
        self.add_assistant(TranslationAssistant("105", "翻译精灵", "v2.1", False, 95, "中-英/日/韩", True))
    
    def add_assistant(self, assistant):
        """添加新的AI助手"""
        if len(self._assistants) >= self._MAX_SIZE:
            print("❌ 助手数量已达到上限，无法添加新助手。")
            return False
        
        # 检查ID是否已存在
        for a in self._assistants:
            if a.id == assistant.id:
                print(f"❌ ID为{assistant.id}的助手已存在。")
                return False
        
        self._assistants.append(assistant)
        print(f"✅ 助手【{assistant.name}】添加成功！")
        return True
    
    def find_assistant_by_id(self, id):
        """根据ID查找AI助手"""
        for assistant in self._assistants:
            if assistant.id == id:
                return assistant
        return None
    
    def delete_assistant_by_id(self, id):
        """根据ID删除AI助手"""
        assistant = self.find_assistant_by_id(id)
        if assistant:
            name = assistant.name
            self._assistants.remove(assistant)
            print(f"✅ 助手【{name}】已删除。")
            return True
        print(f"❌ 未找到ID为{id}的助手。")
        return False
    
    def modify_assistant(self, id, property_name, property_value):
        """修改AI助手的信息"""
        assistant = self.find_assistant_by_id(id)
        if not assistant:
            print(f"❌ 未找到ID为{id}的助手。")
            return False
        
        modified = False
        if property_name.lower() == "name":
            assistant.name = property_value
            modified = True
        elif property_name.lower() == "type":
            # 类型不允许直接修改，因为涉及到对象类型
            print("❌ 助手类型不允许直接修改。")
            return False
        elif property_name.lower() == "version":
            assistant.version = property_value
            modified = True
        elif property_name.lower() == "online":
            assistant.online = property_value == "1" or property_value.lower() == "true"
            modified = True
        elif property_name.lower() == "score":
            try:
                score = float(property_value)
                if 0 <= score <= 100:
                    assistant.score = score
                    modified = True
                else:
                    print("❌ 能力评分必须在0-100之间。")
                    return False
            except ValueError:
                print("❌ 能力评分必须是数字。")
                return False
        else:
            print(f"❌ 不支持修改的属性：{property_name}")
            return False
        
        if modified:
            print(f"✅ 助手【{id}】修改成功！")
            return True
        return False
    
    def start_assistant_service(self, id):
        """启动AI助手服务"""
        assistant = self.find_assistant_by_id(id)
        if not assistant:
            print(f"❌ 未找到ID为{id}的助手。")
            return False
        assistant.start_service()
        return True
    
    def stop_assistant_service(self, id):
        """停止AI助手服务"""
        assistant = self.find_assistant_by_id(id)
        if not assistant:
            print(f"❌ 未找到ID为{id}的助手。")
            return False
        assistant.stop_service()
        return True
    
    def assign_task_to_assistant(self, id, task_content):
        """为AI助手分配任务"""
        assistant = self.find_assistant_by_id(id)
        if not assistant:
            print(f"❌ 未找到ID为{id}的助手。")
            return False
        return assistant.assign_task(task_content)
    
    def display_all_assistants(self):
        """显示所有AI助手的列表"""
        if not self._assistants:
            print("当前没有任何AI助手。")
            return
        print("所有AI助手列表：")
        for i, assistant in enumerate(self._assistants, 1):
            assistant.display_brief_info(i)
    
    def display_assistant_detail(self, id):
        """根据ID显示AI助手的详细信息"""
        assistant = self.find_assistant_by_id(id)
        if not assistant:
            print(f"❌ 未找到ID为{id}的助手。")
            return
        assistant.display_info()
    
    def display_system_statistics(self):
        """显示系统统计信息"""
        if not self._assistants:
            print("系统统计信息：")
            print("总助手数: 0")
            return
        
        online_count = sum(1 for a in self._assistants if a.online)
        total_score = sum(a.score for a in self._assistants)
        avg_score = total_score / len(self._assistants)
        
        print("系统统计信息：")
        print(f"总助手数: {len(self._assistants)}")
        print(f"在线助手数: {online_count}")
        print(f"离线助手数: {len(self._assistants) - online_count}")
        print(f"平均能力评分: {avg_score:.2f}")
    
    def run(self):
        """运行AI助手管理器的主菜单"""
        import sys
        
        print("欢迎使用 AI助手管理器 v1.0")
        
        while True:
            self.display_menu()
            choice = input("请选择操作: ").strip()
            
            if choice == "1":
                self.display_all_assistants()
            elif choice == "2":
                query_id = input("请输入要查询的AI助手ID: ").strip()
                self.display_assistant_detail(query_id)
            elif choice == "3":
                self.add_new_assistant()
            elif choice == "4":
                self.modify_assistant_info()
            elif choice == "5":
                delete_id = input("请输入要删除的AI助手ID: ").strip()
                self.delete_assistant_by_id(delete_id)
            elif choice == "6":
                start_id = input("请输入要启动的AI助手ID: ").strip()
                self.start_assistant_service(start_id)
            elif choice == "7":
                stop_id = input("请输入要停止的AI助手ID: ").strip()
                self.stop_assistant_service(stop_id)
            elif choice == "8":
                self.assign_task()
            elif choice == "9":
                self.display_system_statistics()
            elif choice == "0":
                print("感谢使用AI助手管理器，再见！")
                break
            else:
                print("❌ 无效的选择，请重新输入。")
    
    def display_menu(self):
        """显示主菜单"""
        print("========== 🤖AI助手管理器 ==========")
        print("1. 查看所有AI助手列表")
        print("2. 根据ID查询助手详情")
        print("3. 添加新的AI助手")
        print("4. 根据ID修改助手信息")
        print("5. 删除AI助手（按ID）")
        print("6. 启动AI助手服务")
        print("7. 停止AI助手服务")
        print("8. 为AI助手分配任务")
        print("9. 显示系统统计信息")
        print("0. 退出系统")
        print("===================================")
    
    def add_new_assistant(self):
        """添加新的AI助手的交互方法"""
        print("添加新AI助手")
        id = input("请输入ID: ").strip()
        name = input("请输入名称: ").strip()
        version = input("请输入版本号: ").strip()
        
        online = False
        while True:
            online_str = input("是否在线？(1-是, 0-否): ").strip()
            if online_str == "1":
                online = True
                break
            elif online_str == "0":
                online = False
                break
            else:
                print("❌ 输入错误，请重新输入1或0。")
        
        score = 0
        while True:
            score_str = input("请输入能力评分(0-100): ").strip()
            try:
                score = float(score_str)
                if 0 <= score <= 100:
                    break
                else:
                    print("❌ 能力评分必须在0-100之间。")
            except ValueError:
                print("❌ 请输入有效的数字。")
        
        # 这里简化处理，默认添加文本生成助手，实际应用中可以让用户选择类型
        self.add_assistant(TextGenerationAssistant(id, name, version, online, score, "中文/英文", True))
    
    def modify_assistant_info(self):
        """修改助手信息的交互方法"""
        print("修改AI助手数据")
        id = input("请输入ID: ").strip()
        
        assistant = self.find_assistant_by_id(id)
        if not assistant:
            print(f"❌ 未找到ID为{id}的助手。")
            return
        
        print("可修改属性列表为：name,type,version,online,score")
        input_str = input("请输入要修改的属性和值，用空格分割: ").strip()
        parts = input_str.split(" ", 1)
        if len(parts) < 2:
            print("❌ 输入格式错误，请使用 '属性名 属性值' 的格式。")
            return
        property = parts[0]
        value = parts[1]
        self.modify_assistant(id, property, value)
    
    def assign_task(self):
        """分配任务的交互方法"""
        id = input("请输入目标AI助手ID: ").strip()
        task = input("请输入任务内容: ").strip()
        self.assign_task_to_assistant(id, task)